jQuery(document).ready(function() {
	if($('#google_map_add_form').length){
		var lat = ( $('#lat').val() ) ? $('#lat').val() : 36;
		var lng = ( $('#long').val() ) ? $('#long').val() : 138;
		initialize(lat , lng);
	}
	$('#city').live('change',function(){
		$value = $('#city :selected').text();
		codeAddress($value);
	});
	
	$('.row .right #details').live('focusout',function(){ 
		getLocation();
	});
	//scrollalert();
	
});

function getLocation(){  
	$detail = $('.row .right #details').val();  
	if($('#city :selected').val() != 0){
		$value = $('#city :selected').text();
		$val = $value+' '+$detail;
	}else{
		$val = $detail;
	}	
	 
	codeAddress($val);
}

function scrollalert(){
	if(page== -1 || !$('#mcs_container').length ) return false;
	
	$.post(BASE_URI+'ranking/readmore',{page:page,mode:mode},function(res){
		if(res=='empty'){page=-1; return;};
		$('.row').append(res);
		page++;
		
		var r= $('.dragger_container>.dragger').css('top'); 
		r = parseInt(r);
		var rr= $('.container').css('top'); 
		rr = parseInt(rr);
		
		$('#mcs_container .content').css('min-height', $('#mcs_container .content').height()+350 );
		$("#mcs_container").mCustomScrollbar("vertical",600,"easeOutCirc",1.05,"auto","yes","yes",10);
		
		$('.dragger_container>.dragger').css('top',r+0);
		$('.container').css('top',rr);
		update_height();
	});
	setTimeout('scrollalert();', 2000);
}

var geocoder;
var map;
var marker;
var count=0;

function initialize(lat , lng) {
	geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat,lng);
    var myOptions = {
      zoom: 5,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("google_map_add_form"), myOptions);
    google.maps.event.addListener(map, 'click', function(event) {
    	mapEditor(event.latLng);
    });
    marker = new google.maps.Marker({
		  position: latlng,
		  map: map
	  });
 }

function mapEditor(location) {
    marker.setPosition(location);
	$('#lat').val( location.lat() ); 
	$('#long').val( location.lng() ); 
}

function codeAddress(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(14);
        marker.setPosition(results[0].geometry.location);
        $('#lat').val( results[0].geometry.location.lat() ); 
		$('#long').val( results[0].geometry.location.lng() ); 
      } else {
        //alert("Geocode was not successful for the following reason: " + status);
      }
    });
 }


function selectCities(value){
	$.post( BASE_URI+'ranking/aj_get_cities' , {region_id:value} , function(response){
		$('#city_').html(response);
	} );
}


function new_item(){
	if(json_AUTHOR== null){
		$('#login_err_msg').dialog(
				{ 
					dialogClass: 'rank_alert',
					 buttons: [
						           {
						               text: "OK",
						               click: function() { $(this).dialog("close"); }
						           }
					           ] 
				}
			);
			for_ie();
		return false;
	}
	else{
		window.location = BASE_URI + 'ranking/create_new_item/'+json_AUTHOR.tokenID;
	}
}


function post_ranking(){
	if(json_AUTHOR== null){
		$('#login_err_msg').dialog(
				{ 
					dialogClass: 'rank_alert',
					 buttons: [
					           {
					               text: "OK",
					               click: function() { $(this).dialog("close"); }
					           }
				           ] 
				}
		);
		for_ie();
		return false;
	}
	else{
		var upper_connection_list_id= CFG_arr_high_rank_id.join(',');
		var standard_connection_list_id= sessionStorage.standard_rank_TEMP;
		var lower_connection_list_id= CFG_arr_lower_rank_id.join(',');
		
		if( 0== standard_connection_list_id || standard_connection_list_id == null ){
			$('#report_violate_msg').html(submit_violate_msg);
			$('#report_violate_msg').dialog(
				{ 
					dialogClass: 'rank_alert',
					 buttons: [
					           {
					               text: "OK",
					               click: function() { $(this).dialog("close"); }
					           }
				           ] 
				}
			);
			for_ie();
			return false;
		}
		
		if(!upper_connection_list_id && !lower_connection_list_id){
			$('#report_violate_msg').html(submit_violate_msg);
			$('#report_violate_msg').dialog(
					{ 
						dialogClass: 'rank_alert',
						 buttons: [
						           {
						               text: "OK",
						               click: function() { $(this).dialog("close"); }
						           }
					           ] 
					}
				);
				for_ie();
			return false;
		}
		
		$.post(BASE_URI+ 'ranking/get_connection_info',
				{upper:upper_connection_list_id,
				standard:standard_connection_list_id,
				lower:lower_connection_list_id},function(res){
					$('#report_violate_msg').html(res);
					$('#report_violate_msg').dialog(
							{ 
								dialogClass: 'rank_alert',
								 buttons: [
								           {
								               text: "OK",
								               click: function() { $(this).dialog("close"); }
								           }
							           ] 
							}
					);
					for_ie();
					// free all
					removeAll( CFG_arr_high_rank_id );
					removeAll( CFG_arr_lower_rank_id );
					sessionStorage.setItem('standard_rank_TEMP',0);
					
					$('#dropable_high').html('');
					$('#dropable_standard').html('');
					$('#dropable_low').html('');
					
					sessionStorage.removeItem('rank_post_arrays');
			   });
	}
}

function submit_form_add_item(){
	var error = 0;
	$("input").each(function(){
		if(this.required && this.value ==''){
			$(this).addClass("error"); error ++;
		}else{
			$(this).removeClass("error");
		} 
		
	}); 
/*	
	var iRegion = parseInt( $('#region').val() );
	var iCity = parseInt ( $('#city').val() );
	if(iRegion * iCity == 0){
		error ++;
		if(iRegion == 0)
			$('#region').addClass("error");
		else
			$('#region').removeClass("error");
		
		if(iCity == 0)
			$('#city').addClass("error");
		else
			$('#city').removeClass("error");
	}else{
		$('#city').removeClass("error");
		$('#region').removeClass("error");
	}
*/	
/*	var count =0;var i = 1;
	$('input[rel="select_image"]').each(function(){
		isChecked = ( $(this).attr('checked') ) ? true : false;
		var img = $('#image_uploaded_'+i).val(); i++;
		if(isChecked && img) {
			count++;
			$('#selected_image_err').removeClass("error"); 
			$('#selected_image_err').addClass("hidden");
		}
	});
	 
	if( 0 == count ){
		$('#selected_image_err').removeClass("hidden"); 
		$('#selected_image_err').addClass("error");
		error ++;
	}else{
		$('#selected_image_err').removeClass("error"); 
		$('#selected_image_err').addClass("hidden");
	 
	}
	
	if(!isUrl( $('#user_url').val() )){
		$('#user_url').addClass('error');
		error ++;
	}else{
		$('#user_url').removeClass('error');
	}
*/	
	if(!isEmpty($('#user_url').val())){
		if(!isUrl( $('#user_url').val() )){
			$('#user_url').addClass('error');
			error ++;
		}else{
			$('#user_url').removeClass('error');
		}
	}
	
	var ichecked = $('input[name="image_selected"]:checked').val();
	var img = $('#image_uploaded_'+ichecked).val(); 
	if(!img){
		$('#selected_image_err').removeClass("hidden"); 
		$('#selected_image_err').addClass("error");
		error ++;
	}else{
		$('#selected_image_err').removeClass("error"); 
		$('#selected_image_err').addClass("hidden");
	}
	
	
	
	if(isEmpty($('#image_uploaded_1').val()) && isEmpty($('#image_uploaded_2').val()) && isEmpty($('#image_uploaded_3').val()) ){
		error ++;
		$('#image_upload_stt1').children().removeClass('hidden');
		$('#image_upload_stt1').children().addClass('error');
	}else{
		$('#image_upload_stt1').children().removeClass('error');
		$('#image_upload_stt1').children().addClass('hidden');
	}
/*	
	if(isEmpty( $('#image_uploaded_2').val() )){
		error ++;
		$('#image_upload_stt2').children().removeClass('hidden');
		$('#image_upload_stt2').children().addClass('error');
	}else{
		$('#image_upload_stt2').children().removeClass('error');
		$('#image_upload_stt2').children().addClass('hidden');
	}
	
	if(isEmpty( $('#image_uploaded_3').val() )){
		error ++;
		$('#image_upload_stt3').children().removeClass('hidden');
		$('#image_upload_stt3').children().addClass('error');
	}else{
		$('#image_upload_stt3').children().removeClass('error');
		$('#image_upload_stt3').children().addClass('hidden');
	}
*/
	
	if(error == 0){
		$('#form_post_an_item').submit();
	/**	
		$('#check_duplicate_name').removeClass("hidden");
		$.post( BASE_URI +'ranking/aj_check_duplicate_name' ,{name:$('#name_item').val(),'item_id':$('#item_id').val()} , function(response){
			if(response == 'ok'){
				$('#check_duplicate_name').addClass("hidden");
				$('#form_post_an_item').submit();
			}else{
				$('#check_duplicate_name').addClass("hidden");
				$('#check_duplicate_name_error').removeClass("hidden");
				window.location.href= '#name_item';
				return false;
			}
			
		} );
	**/	
	}else{
		return false;
	}
	
}

function select_image(me, select_pos){
	var isChecked = ($(me).attr('checked')) ? true :false;
	$('input[rel="select_image"]').each(function(){
		$(this).attr('checked',false);
	});
	if(isChecked){
		$(me).attr('checked',true);
	}
}

/*
function google_image_search(){
	var qk = $('#google_image').val();
	$url = "http://images.google.com/search?tbm=isch&hl=jp&source=hp&biw=1280&bih=610&q="+qk+"&gbv=2&oq="+qk+"&aq=f&aqi=g10&aql=&gs_sm=e";
	window.open($url);
}
*/

function fileUpload(form, action_url, div_id, div_preview, upload_frame_id)
{
	 var mainForm = document.form_post_an_item.action;
	// Create the iframe...
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id",upload_frame_id);
	iframe.setAttribute("name",upload_frame_id);
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","0");
	iframe.setAttribute("style","width: 0; height: 0; border: none;");
	
	// Add to document...
	form.parentNode.appendChild(iframe);
	window.frames[upload_frame_id].name=upload_frame_id;
	
	iframeId = document.getElementById(upload_frame_id);
	
	// Add event...
	var eventHandler = function()  {
	
		if (iframeId.detachEvent)
			iframeId.detachEvent("onload", eventHandler);
		else
			iframeId.removeEventListener("load", eventHandler, false);
		
		// Message from server...
		if (iframeId.contentDocument) {
			content = iframeId.contentDocument.body.innerHTML;
		} else if (iframeId.contentWindow) {
			content = iframeId.contentWindow.document.body.innerHTML;
		} else if (iframeId.document) {
			content = iframeId.document.body.innerHTML;
		}
		
		arr = content.split('SEP_CHAR');  
		if(arr[0] != 'error'){
		 	document.getElementById(div_preview).innerHTML = arr[1]; 
			document.getElementById(div_id).innerHTML = '';
			document.getElementById(arr[2]).value= arr[3];
		}	
		else{
			document.getElementById(div_id).innerHTML =  arr[1];
			document.getElementById(arr[2]).value= arr[3];
			
			form.value = '';
		}
			
		// Del the iframe...
		setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
		
		//Reset properties of form...
		form.setAttribute("target",'');
		form.setAttribute("action",mainForm);
		form.setAttribute("method","post");
		form.setAttribute("enctype","");
		form.setAttribute("encoding","");
	}
	
	if (iframeId.addEventListener)
		iframeId.addEventListener("load", eventHandler, true);
	if (iframeId.attachEvent)
		iframeId.attachEvent("onload", eventHandler);
	
	// Set properties of form...
	form.setAttribute("target",upload_frame_id);
	form.setAttribute("action", BASE_URI+'ranking/'+ action_url);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	
	// Submit the form...
	form.submit();
	
	document.getElementById(div_id).innerHTML = sessionStorage.uploading;
}

function get_GMAP(lat,lng ){
	var latlng = new google.maps.LatLng( lat, lng );
    var myOptions = {
      zoom: 5,
      center: latlng,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var  mapM = new google.maps.Map(document.getElementById("googleMap"),  myOptions)
	var markerM = new google.maps.Marker({
  		  position: latlng,
  		  map: mapM
  	});
   
}

function open_POPUP(id){
	$.getScript( BASE_URI + 'ranking/js_get_info?id='+id , function(data, textStatus){
			$('#info').html(JS_info_title);
			
			$('#images').html('');
			if(JS_info_image1 != ''){
				$('#images').append( "<img src="+BASE_URI+"uploads/files/timthumb.php?w=72&h=72&zc=1&src="+BASE_URI+"uploads/files/pictures/"+JS_info_image1+" />" );
			}
			if(JS_info_image2 != ''){
				$('#images').append( "<img src="+BASE_URI+"uploads/files/timthumb.php?w=72&h=72&zc=1&src="+BASE_URI+"uploads/files/pictures/"+JS_info_image2+" />" );
			}
			if(JS_info_image3 != ''){
				$('#images').append( "<img src="+BASE_URI+"uploads/files/timthumb.php?w=72&h=72&zc=1&src="+BASE_URI+"uploads/files/pictures/"+JS_info_image3+" />" );
			}
			
			$('#address').html(JS_info_address);
			$('#details').html(JS_info_details);
			$('#url').html(JS_info_url);
			$('#link_map').html(JS_info_underMap_link);
			
		   $('#open_POPUP').dialog({
				   resizable: false,
				   width: 554,
				   height:298,
				   dialogClass: 'rank_alert',
				   close: function(event, ui) { 
			   			$('#info').html('');
			   			$('#images').html('');
			   			$('#address').html('');
			   			$('#details').html('');
			   			$('#url').html('');
			   			$('#googleMap').html('');
			   			$('#open_POPUP').dialog( "destroy" );
		   		   }
		   		}
		   );
			for_ie();
		   get_GMAP(JS_info_lat, JS_info_lng ) ;
	});
}

function report_violate(){
	$('#report_violate_msg').dialog( "close" );
	if(JS_info_mofidy_id == 0){
		$('#login_err_msg').dialog(
				{ 
					dialogClass: 'rank_alert',
					 buttons: [
					           {
					               text: "OK",
					               click: function() { $(this).dialog("close"); }
					           }
				           ] 
				}		
		);
		for_ie();
		return false;
	}else{
		//send one email to admin report violate
		$.getScript( BASE_URI + 'ranking/js_report_violate?id='+JS_info_id+'&user_id='+JS_info_mofidy_id , function(data, textStatus){
			$('#report_violate_msg').html(JS_info_report_status);
			$('#report_violate_msg').dialog({ dialogClass: 'rank_alert'});for_ie();
		});
	}
}

function update_item(){
	if(json_AUTHOR== null){
		$('#login_err_msg').dialog(
				{ 
					dialogClass: 'rank_alert',
					 buttons: [
					           {
					               text: "OK",
					               click: function() { $(this).dialog("close"); }
					           }
				           ] 
				}	
		);
		for_ie();
		return false;
	}else{
		window.location = BASE_URI+'ranking/update_item?item_id='+JS_info_id+'&user_id='+JS_info_mofidy_id;
	}
}



jQuery(document).ready(function() {
	$('#name_item').bind('keyup',function(){
		$valueOfName = $('#name_item').val();
		$('#google_image').attr('value',$valueOfName);
	});
	$('#dish_name').bind('keyup',function(){
		$valueOfName = $('#name_item').val();
		$valueOfDish = $('#dish_name').val();
		$('#google_image').attr('value',$valueOfName+' '+$valueOfDish);
	});
	$('#name_item').bind('focusout',function(){
		google_image_search();
	});
	$('#dish_name').bind('focusout',function(){
	    google_image_search();
	});
	$('#google_image_button').bind('click',function(){
		$('body').data('click_num', 1);
	});
	
	if($('#modify_user_id').length){
		google_image_search();
	}
});


google.load('search', '1');
var imageSearch;
var imagePosArray = 0;
var result_gb = [];
var oldKey = "";

function searchComplete() {
	var cursor = imageSearch.cursor;
    var curPage = cursor.currentPageIndex; // check what page the app is on
	
	if (imageSearch.results && imageSearch.results.length > 0) {
	  var results = imageSearch.results;
	  for (var i = 0; i < results.length; i++) {
		var objCollect_gb = {};
		var result = results[i];
		
		objCollect_gb.src = result.tbUrl;
		objCollect_gb.orgUrl = result.originalContextUrl;
		objCollect_gb.urlImg = result.url;
		result_gb.push(objCollect_gb);
	  }
	}
	
	imageSearch.gotoPage(curPage+1);
	if(curPage == cursor.pages.length-1){
		if($('#item_id').length == 0 || $('body').data('click_num')== 1)
			displayGoogleImage();
	}
	
}

	  
function google_image_search(){
	$key = $('#google_image').val();
	
	imageSearch = new google.search.ImageSearch();
	imageSearch.setSearchCompleteCallback(this, searchComplete, null);
	imageSearch.setResultSetSize(6);
	
	if($key != oldKey){ 
		imageSearch.clearResults();
		result_gb = [];
		imagePosArray = 0;	
		oldKey= $key;  
	}
	imageSearch.execute($key);	
}

function displayGoogleImage(){
	if(result_gb.length == 0){
		google_image_search();
	}
	var t = imagePosArray;
	for(var j=1; j<=3; j++){
		$('.wrap-170 #preview_'+j).html("<img src='"+result_gb[t+j].src+"' />");
		$('#image_uploaded_'+j).attr('value',result_gb[t+j].urlImg);
		imagePosArray++;
		if(imagePosArray >= result_gb.length-1){
			google_image_search();
		}
	}

}

function select_image_google_API($this, $id){
	var t = imagePosArray; 
	$('.wrap-170 #preview_'+$id).html("<img src='"+result_gb[t+1].src+"' />");
	$('#image_uploaded_'+$id).attr('value',result_gb[t+1].urlImg);
	
	imagePosArray += 1;
	if(imagePosArray >= result_gb.length-1){
		google_image_search();
	}
}

/***
// Deprecated. Only use for Firefox 3.x
function preview_image(divFile,divShow){
	var maxWidth=150;
	var maxHeight=100;
	var fileTypes=["bmp","gif","png","jpg","jpeg"];
	
	if( document.getElementById(divFile).files) {
		var filename = document.getElementById(divFile).files.item(0).fileName;
		var filesize = document.getElementById(divFile).files.item(0).fileSize;
		var filesource = document.getElementById(divFile).files.item(0).getAsDataURL();
		
		var ext=filename.substring(filename.lastIndexOf(".")+1,filename.length).toLowerCase(); 
		 
		if (fileTypes.in_array(ext)){
			
		}else{ 
			$("#file_err_msg").dialog(); return false;
		}
		 
		if( filesize/100 > parseInt($('#max_file_size').val()) ){
			 $("#file_err_msg").dialog(); return false;
		}
		 
		$('#'+divShow).html("<img src='"+filesource+"' width='"+maxWidth+"' height='"+maxHeight+"' />"); 
	}else{
		return false;
	} 
}

***/


